import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
import { h } from "vue";
import { ElNotification } from "element-plus";
import cf from "@/cf";

const open1 = (message: string) => {
  ElNotification({
    title: "消息",
    message: h("i", { style: "color: teal" }, message),
    duration: 5000,
  });
};

let connection: any = null;

export const useSignalR = () => {
  // 初始化连接
  const startConnection = async (token: string) => {
    try {
      connection = new HubConnectionBuilder()
        .withUrl(cf.CHAT_HUB_URL, {
          accessTokenFactory: () => "Bearer " + token, // 注入 Token
        })
        .configureLogging(LogLevel.Information)
        .withAutomaticReconnect() // 自动重连
        .build();

      await connection.start();
      console.log("SignalR 连接成功");

      // 注册接收消息的处理器
      connection.on("ReceiveMessage", handleMessage);
    } catch (err) {
      console.error("SignalR 连接失败:", err);
    }
  };

  // 断开连接
  const stopConnection = async () => {
    if (connection) {
      await connection.stop();
      connection = null;
      console.log("SignalR 已断开");
    }
  };

  // 处理接收的消息（示例）
  const handleMessage = (message: string) => {
    open1(message);
    // 可通过 Pinia 更新状态或触发事件
  };

  return {
    connection,
    startConnection,
    stopConnection,
  };
};
